package cn.jn.lhm.netty.part07;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/10/29 - 21:39
 **/
@SuppressWarnings("all")
@Slf4j
public class ShortConnectServer {

    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // 配置系统的接收缓冲区(滑动窗口)
            // serverBootstrap.option(ChannelOption.SO_RCVBUF, 10);
            ChannelFuture future = serverBootstrap.channel(NioServerSocketChannel.class)
                    .group(boss, worker)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel client) throws Exception {
                            ByteBuf buffer = client.alloc().buffer();
                            //client.pipeline().addLast(new LineBasedFrameDecoder(256));
                            //client.pipeline().addLast(new FixedLengthFrameDecoder(256));
                            client.pipeline().addLast(new DelimiterBasedFrameDecoder(256, buffer.writeBytes("\t".getBytes())));
                            client.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        }
                    })
                    .bind(8080)
                    .sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("server Error...", e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
